package ynet

import (
	"fmt"
	"net"
	"yigo/yiface"
)

// Connection :
type Connection struct {
	// connection socket
	Conn *net.TCPConn

	// connection id
	ConnID uint32

	//connection status
	IsClosed bool

	//api for handling  service
	HandleAPI yiface.HandleFunc

	//mark exiting status channel
	ExitChan chan bool
}

//Start : start connection
func (o *Connection) Start() {
	fmt.Println(" Connection is starting ")
	// starting read data service

	// starting write data service

}

//StartRead : start connection
func (o *Connection) StartRead() {
	fmt.Println(" Connection reader is starting ")
	// starting read data service
	defer o.Stop()

	for {
		buf := make([]byte, 512)
		len, err := o.Conn.Read(buf)
		if err != nil {
			fmt.Println("Connection read error : ", err)
			continue
		}
		if err := o.HandleAPI(o.Conn, buf, len); err != nil {
			break
		}
	}
}

//StartWrite : start connection
func (o *Connection) StartWrite() {
	fmt.Println(" Connection writer is starting ")
	// starting read data service
	go o.StartRead()
	// starting write data service
	go o.StartWrite()
}

//Stop : stop connection
func (o *Connection) Stop() {
	fmt.Println("Connection is stopping ")
	if o.IsClosed == true {
		return
	}
	o.IsClosed = true
	o.Conn.Close()
	close(o.ExitChan)
}

//GetTCPConnection : get  socket conn from current connection
func (o *Connection) GetTCPConnection() *net.TCPConn {

}

//GetConnID : get connection id
func (o *Connection) GetConnID() {

}

//GetRemoteAddr : get  client's id and port
func (o *Connection) GetRemoteAddr() net.Addr {

}

//Send : send message to client
func (o *Connection) Send(data []byte) error {

}

//NewConnection :  initialize connection
func NewConnection(conn *net.TCPConn, connID uint32, callbackAPI yiface.HandleFunc) *Connection {
	return &Connection{
		Conn:      conn,
		ConnID:    connID,
		IsClosed:  false,
		HandleAPI: callbackAPI,
		ExitChan:  make(chan bool, 1),
	}
}
